﻿uniform sampler2D tex;
uniform vec3 axis;
uniform vec3 eye;

const float K_d = 1.0;
const vec3 K_s = vec3(0.2, 0.2, 0.2);
const float shininess = 150.0;

varying vec4 pos;

float vecSin(vec4 a, vec4 b) // a and b are normalized
{
	return length(a - dot(a, b) * b);
}

void main()
{
	vec4 color = texture2D( tex, gl_TexCoord[0].st );
	vec4 matSpec = gl_FrontMaterial.specular;
	vec4 lightSpec = gl_LightSource[0].specular;
	
	color[0] = 0.55;
	color[1] = 0.26;
	color[2] = 0.13;
	
	//vec4 l = normalize( vec4(5, 0, 5, 1) - pos );
	
	//vec4 t =  vec4(axis, 1);
	//
	//vec4 l = gl_LightSource[0].position - pos;
	//
	//float costheta = dot(t, l) / (length(t) * length(l));
	//
	//float sintheta = sqrt(1 - (costheta * costheta));
	//
	//float intensity = K_d * sintheta; // sin(t, l)
	//
	//color[0] = intensity * (1.0 - color[0]);
	//color[1] = intensity * (1.0 - color[1]);
	//color[2] = intensity * (1.0 - color[2]);
	
	vec4 t = normalize( vec4(axis, 1) );
	
	vec4 l = normalize( gl_LightSource[0].position - pos );
	
	float intensity = K_d * vecSin(t, l); // sin(t, l)
	
	color.xyz = intensity * color.xyz;
	
	vec4 e = normalize( vec4( eye, 1 ) - pos );
	
	float dotTL = dot( t, l );
	float dotTE = dot( t, e );
	//float sinTL = vecSin( t, l );
	//float sinTE = vecSin( t, e );
	float sinTL = sqrt( 1 - dotTL * dotTL );
	float sinTE = sqrt( 1 - dotTE * dotTE );
	
	vec3 specular = K_s * pow( dotTL * dotTE + sinTL * sinTE, shininess );
	
	color += vec4( specular, color[3] );
	
	gl_FragColor = color;
}